import React, { useMemo } from 'react'
import { Button, Card, DatePicker, Form, Input, Select, Space, Table, Tag, Modal, InputNumber, Popconfirm, message } from 'antd'
import dayjs from 'dayjs'

type OutboundRecord = {
  key: React.Key
  index: number
  orderNo: string
  type: string
  status: '草稿' | '待审核' | '已完成'
  date: string
  warehouse: string
  relatedNo: string
  customer: string
  contact: string
  phone: string
  goods: string
  qty: number
  amount: number
  agent: string
  maker: string
  department: string
  makeTime: string
}

// 列定义已改为内联构造，移除旧的常量定义以避免未使用的 lint 告警

const mockData: OutboundRecord[] = Array.from({ length: 60 }).map((_, i) => ({
  key: i + 1,
  index: i + 1,
  orderNo: `CKDH${(1800 + i).toString().padStart(4, '0')}`,
  type: ['领用出库', '销售出库', '采购退货', '调拨出库'][i % 4],
  status: (['草稿', '待审核', '已完成'] as OutboundRecord['status'][])[i % 3],
  date: '2024-02-29',
  warehouse: '货品仓库一',
  relatedNo: 'XSDH055451',
  customer: '客户一',
  contact: '李依依',
  phone: '13900927580',
  goods: '三锅头、可笑、何必等8项……',
  qty: 50,
  amount: 9999,
  agent: '赵依依',
  maker: ['甄惜梦','稳款美','凄雨柏','宗政欣欣','乌雅恭','刑素怀','星飞虎','令乐','苟冰蝶','令狐丽泽'][i % 10],
  department: '仓储部',
  makeTime: '2024-02-29 21:35:55'
}))

export default function ToStorage() {
  const [form] = Form.useForm()
  const [dataSource, setDataSource] = React.useState(mockData)
  const [selectedRowKeys, setSelectedRowKeys] = React.useState<React.Key[]>([])
  const [addOpen, setAddOpen] = React.useState(false)
  const [adding, setAdding] = React.useState(false)
  const [addForm] = Form.useForm<Partial<OutboundRecord>>()
  const [pagination, setPagination] = React.useState({ current: 1, pageSize: 10 })
  const [editOpen, setEditOpen] = React.useState(false)
  const [editingKey, setEditingKey] = React.useState<React.Key | null>(null)
  const [editForm] = Form.useForm<Partial<OutboundRecord>>()

  const handleSearch = () => {
    const { orderNo, type, status, date, warehouse, customer } = form.getFieldsValue()
    const filtered = mockData.filter((r) => {
      const byOrder = orderNo ? r.orderNo.includes(orderNo) : true
      const byType = type ? r.type === type : true
      const byStatus = status ? r.status === status : true
      const byDate = date ? r.date === dayjs(date).format('YYYY-MM-DD') : true
      const byWh = warehouse ? r.warehouse === warehouse : true
      const byCus = customer ? r.customer.includes(customer) : true
      return byOrder && byType && byStatus && byDate && byWh && byCus
    })
    setDataSource(filtered)
    setPagination((p) => ({ ...p, current: 1 }))
    message.success(`查询到 ${filtered.length} 条结果`)
  }

  const handleReset = () => {
    form.resetFields()
    setDataSource(mockData)
    setPagination((p) => ({ ...p, current: 1 }))
  }

  const disabledBySelection = useMemo(() => selectedRowKeys.length === 0, [selectedRowKeys])

  const openAdd = () => {
    addForm.resetFields()
    addForm.setFieldsValue({
      type: '销售出库',
      date: dayjs(),
      warehouse: '货品仓库一',
      qty: 1,
      amount: 0,
      status: '草稿'
    } as any)
    setAddOpen(true)
  }

  const submitAdd = async () => {
    try {
      const values = await addForm.validateFields()
      setAdding(true)
      const nextIndex = dataSource.length + 1
      const newRecord: OutboundRecord = {
        key: Date.now(),
        index: nextIndex,
        orderNo: `CKDH${(3000 + nextIndex).toString().padStart(4, '0')}`,
        type: values.type!,
        status: values.status as OutboundRecord['status'],
        date: dayjs(values.date).format('YYYY-MM-DD'),
        warehouse: values.warehouse!,
        relatedNo: values.relatedNo || '—',
        customer: values.customer || '—',
        contact: values.contact || '—',
        phone: values.phone || '—',
        goods: values.goods || '—',
        qty: Number(values.qty || 0),
        amount: Number(values.amount || 0),
        agent: values.agent || '—',
        maker: values.maker || '—',
        department: values.department || '—',
        makeTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
      }
      setDataSource((prev) => [newRecord, ...prev.map((p, i) => ({ ...p, index: i + 2 }))])
      setAddOpen(false)
      message.success('新增成功')
    } finally {
      setAdding(false)
    }
  }

  const handleDelete = () => {
    setDataSource((prev) => prev.filter((r) => !selectedRowKeys.includes(r.key)).map((r, i) => ({ ...r, index: i + 1 })))
    setSelectedRowKeys([])
    message.success('删除成功')
  }

  const handleCopy = () => {
    setDataSource((prev) => {
      const copies = prev.filter((r) => selectedRowKeys.includes(r.key)).map((r) => ({ ...r, key: `${r.key}-c-${Date.now()}`, orderNo: `${r.orderNo}-C`, status: '草稿' as const }))
      const next = [...copies, ...prev]
      return next.map((r, i) => ({ ...r, index: i + 1 }))
    })
    message.success('复制成功')
  }

  const handleAudit = () => {
    setDataSource((prev) => prev.map((r) => (selectedRowKeys.includes(r.key) ? { ...r, status: '已完成' } : r)))
    message.success('审核完成')
  }

  const handleRevoke = () => {
    setDataSource((prev) => prev.map((r) => (selectedRowKeys.includes(r.key) ? { ...r, status: '草稿' } : r)))
    message.success('已撤销为草稿')
  }

  const handleExport = () => {
    const headers = ['序号','出库单号','出库类型','状态','出库日期','仓库名称','关联单号','客户名称','联系人','联系方式','出库货品','出库数量','出库金额','经办人','制单人','所在部门','制单时间']
    const rows = dataSource.map((r) => [r.index, r.orderNo, r.type, r.status, r.date, r.warehouse, r.relatedNo, r.customer, r.contact, r.phone, r.goods, r.qty, r.amount, r.agent, r.maker, r.department, r.makeTime])
    const csv = [headers.join(','), ...rows.map((row) => row.map((v) => `"${String(v ?? '').replace(/"/g, '""')}"`).join(','))].join('\n')
    const blob = new Blob(["\ufeff" + csv], { type: 'text/csv;charset=utf-8;' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `出库管理_${dayjs().format('YYYYMMDD_HHmmss')}.csv`
    a.click()
    URL.revokeObjectURL(url)
  }

  const handleRefresh = () => {
    setDataSource(mockData)
    setSelectedRowKeys([])
    message.success('已刷新')
  }

  const handleRowDelete = (key: React.Key) => {
    setDataSource((prev) => prev.filter((r) => r.key !== key).map((r, i) => ({ ...r, index: i + 1 })))
    message.success('已删除')
  }

  const openEdit = (record: OutboundRecord) => {
    setEditingKey(record.key)
    editForm.setFieldsValue({
      ...record,
      date: dayjs(record.date)
    } as any)
    setEditOpen(true)
  }

  const submitEdit = async () => {
    const values = await editForm.validateFields()
    const updated: Partial<OutboundRecord> = {
      ...values,
      date: values.date ? dayjs(values.date as any).format('YYYY-MM-DD') : undefined
    }
    setDataSource((prev) => prev.map((r) => (r.key === editingKey ? { ...r, ...updated } as OutboundRecord : r)))
    setEditOpen(false)
    setEditingKey(null)
    message.success('已保存')
  }

  return (
    <Space direction="vertical" size={12} style={{ width: '100%' }}>
      
      <Card bordered={false} bodyStyle={{ paddingBottom: 0 }}>
        <Form form={form} layout="inline" onFinish={handleSearch}>
          <Form.Item label="出库单号" name="orderNo">
            <Input placeholder="请输入" allowClear style={{ width: 200 }} />
          </Form.Item>
          <Form.Item label="出库类型" name="type">
            <Select
              placeholder="请选择"
              allowClear
              options={[
                { label: '领用出库', value: '领用出库' },
                { label: '销售出库', value: '销售出库' },
                { label: '采购退货', value: '采购退货' },
                { label: '调拨出库', value: '调拨出库' }
              ]}
              style={{ width: 160 }}
            />
          </Form.Item>
          <Form.Item label="单据状态" name="status">
            <Select
              placeholder="请选择"
              allowClear
              options={[
                { label: '草稿', value: '草稿' },
                { label: '待审核', value: '待审核' },
                { label: '已完成', value: '已完成' }
              ]}
              style={{ width: 140 }}
            />
          </Form.Item>
          <Form.Item label="出库日期" name="date">
            <DatePicker style={{ width: 160 }} />
          </Form.Item>
          <Form.Item label="仓库名称" name="warehouse">
            <Select
              placeholder="请选择"
              allowClear
              options={[
                { label: '货品仓库一', value: '货品仓库一' },
                { label: '原料仓库', value: '原料仓库' }
              ]}
              style={{ width: 160 }}
            />
          </Form.Item>
          <Form.Item label="客户名称" name="customer">
            <Input placeholder="请输入" allowClear style={{ width: 160 }} />
          </Form.Item>

          <Space style={{ marginLeft: 'auto', marginBottom: 16 }}>
            <Button onClick={handleReset}>重置</Button>
            <Button type="primary" htmlType="submit">查询</Button>
          </Space>
        </Form>
      </Card>

      <Card bordered={false} bodyStyle={{ paddingTop: 12 }}>
        <Space style={{ marginBottom: 12 }} wrap>
          <Button type="primary" onClick={openAdd}>新增</Button>
          <Popconfirm title="确定删除选中记录吗？" onConfirm={handleDelete} disabled={disabledBySelection}>
            <Button danger disabled={disabledBySelection}>删除</Button>
          </Popconfirm>
          <Button disabled={disabledBySelection} onClick={handleCopy}>复制</Button>
          <Button disabled={disabledBySelection} onClick={handleAudit}>审核</Button>
          <Button disabled={disabledBySelection} onClick={handleRevoke}>撤销</Button>
          <Button onClick={handleExport}>导出</Button>
          <Button onClick={handleRefresh}>刷新</Button>
        </Space>

        <Table
          rowSelection={{ selectedRowKeys, onChange: setSelectedRowKeys }}
          columns={(function() {
            const columns = [
              { title: '序号', dataIndex: 'index', width: 70, fixed: 'left' as const },
              { title: '出库单号', dataIndex: 'orderNo', width: 140, fixed: 'left' as const },
              { title: '出库类型', dataIndex: 'type', width: 110, fixed: 'left' as const },
              {
                title: '状态',
                dataIndex: 'status',
                width: 100,
                fixed: 'left' as const,
                render: (text: OutboundRecord['status']) => {
                  const colorMap: Record<OutboundRecord['status'], string> = { 草稿: 'default', 待审核: 'orange', 已完成: 'green' }
                  return <Tag color={colorMap[text]}>{text}</Tag>
                }
              },
              { title: '出库日期', dataIndex: 'date', width: 120, fixed: 'left' as const },
              { title: '仓库名称', dataIndex: 'warehouse', width: 120 },
              { title: '关联单号', dataIndex: 'relatedNo', width: 140 },
              { title: '客户名称', dataIndex: 'customer', width: 120 },
              { title: '联系人', dataIndex: 'contact', width: 100 },
              { title: '联系方式', dataIndex: 'phone', width: 140 },
              { title: '出库货品', dataIndex: 'goods', ellipsis: true },
              { title: '出库数量', dataIndex: 'qty', width: 100 },
              { title: '出库金额', dataIndex: 'amount', width: 120 },
              { title: '经办人', dataIndex: 'agent', width: 100 },
              { title: '制单人', dataIndex: 'maker', width: 100 },
              { title: '所在部门', dataIndex: 'department', width: 120 },
              { title: '制单时间', dataIndex: 'makeTime', width: 180 },
              {
                title: '操作',
                key: 'action',
                fixed: 'right' as const,
                width: 160,
                render: (_: any, record: OutboundRecord) => (
                  <Space>
                    <Button type="link" size="small" onClick={() => openEdit(record)}>编辑</Button>
                    <Popconfirm title="确认删除该行？" onConfirm={() => handleRowDelete(record.key)}>
                      <Button type="link" size="small">删除</Button>
                    </Popconfirm>
                  </Space>
                )
              }
            ]
            return columns as any
          })()}
          dataSource={dataSource}
          bordered
          size="middle"
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: [10, 20, 50],
            showTotal: (total) => `共 ${total} 条`,
            onChange: (current, pageSize) => setPagination({ current, pageSize })
          }}
          scroll={{ x: 1900 }}
        />
      </Card>
      <Modal
        title="编辑出库单"
        open={editOpen}
        onCancel={() => setEditOpen(false)}
        onOk={submitEdit}
        okText="保存"
        cancelText="取消"
        destroyOnClose
      >
        <Form form={editForm} labelCol={{ span: 6 }} wrapperCol={{ span: 16 }} preserve={false}>
          <Form.Item label="出库类型" name="type" rules={[{ required: true, message: '请选择出库类型' }]}> 
            <Select options={[{ label: '领用出库', value: '领用出库' }, { label: '销售出库', value: '销售出库' }, { label: '采购退货', value: '采购退货' }, { label: '调拨出库', value: '调拨出库' }]} />
          </Form.Item>
          <Form.Item label="出库日期" name="date" rules={[{ required: true, message: '请选择日期' }]}> 
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item label="仓库名称" name="warehouse" rules={[{ required: true, message: '请选择仓库' }]}> 
            <Select options={[{ label: '货品仓库一', value: '货品仓库一' }, { label: '原料仓库', value: '原料仓库' }]} />
          </Form.Item>
          <Form.Item label="关联单号" name="relatedNo"> 
            <Input placeholder="可选" />
          </Form.Item>
          <Form.Item label="客户名称" name="customer"> 
            <Input />
          </Form.Item>
          <Form.Item label="联系人" name="contact"> 
            <Input />
          </Form.Item>
          <Form.Item label="联系方式" name="phone"> 
            <Input />
          </Form.Item>
          <Form.Item label="出库货品" name="goods"> 
            <Input />
          </Form.Item>
          <Form.Item label="出库数量" name="qty" rules={[{ required: true, message: '请输入数量' }]}> 
            <InputNumber min={0} style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item label="出库金额" name="amount" rules={[{ required: true, message: '请输入金额' }]}> 
            <InputNumber min={0} style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item label="经办人" name="agent"> 
            <Input />
          </Form.Item>
          <Form.Item label="制单人" name="maker"> 
            <Input />
          </Form.Item>
          <Form.Item label="所在部门" name="department"> 
            <Input />
          </Form.Item>
          <Form.Item label="单据状态" name="status" rules={[{ required: true, message: '请选择状态' }]}> 
            <Select options={[{ label: '草稿', value: '草稿' }, { label: '待审核', value: '待审核' }, { label: '已完成', value: '已完成' }]} />
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title="新增出库单"
        open={addOpen}
        confirmLoading={adding}
        onCancel={() => setAddOpen(false)}
        onOk={submitAdd}
        okText="保存"
        cancelText="取消"
        destroyOnClose
      >
        <Form form={addForm} labelCol={{ span: 6 }} wrapperCol={{ span: 16 }} preserve={false}>
          <Form.Item label="出库类型" name="type" rules={[{ required: true, message: '请选择出库类型' }]}>
            <Select options={[{ label: '领用出库', value: '领用出库' }, { label: '销售出库', value: '销售出库' }, { label: '采购退货', value: '采购退货' }, { label: '调拨出库', value: '调拨出库' }]} />
          </Form.Item>
          <Form.Item label="出库日期" name="date" rules={[{ required: true, message: '请选择日期' }]}>
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item label="仓库名称" name="warehouse" rules={[{ required: true, message: '请选择仓库' }]}>
            <Select options={[{ label: '货品仓库一', value: '货品仓库一' }, { label: '原料仓库', value: '原料仓库' }]} />
          </Form.Item>
          <Form.Item label="关联单号" name="relatedNo">
            <Input placeholder="可选" />
          </Form.Item>
          <Form.Item label="客户名称" name="customer">
            <Input />
          </Form.Item>
          <Form.Item label="联系人" name="contact">
            <Input />
          </Form.Item>
          <Form.Item label="联系方式" name="phone">
            <Input />
          </Form.Item>
          <Form.Item label="出库货品" name="goods">
            <Input placeholder="如：啤酒、白酒…" />
          </Form.Item>
          <Form.Item label="出库数量" name="qty" rules={[{ required: true, message: '请输入数量' }]}>
            <InputNumber min={0} style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item label="出库金额" name="amount" rules={[{ required: true, message: '请输入金额' }]}>
            <InputNumber min={0} style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item label="经办人" name="agent">
            <Input />
          </Form.Item>
          <Form.Item label="制单人" name="maker">
            <Input />
          </Form.Item>
          <Form.Item label="所在部门" name="department">
            <Input />
          </Form.Item>
          <Form.Item label="单据状态" name="status" rules={[{ required: true, message: '请选择状态' }]}>
            <Select options={[{ label: '草稿', value: '草稿' }, { label: '待审核', value: '待审核' }, { label: '已完成', value: '已完成' }]} />
          </Form.Item>
        </Form>
      </Modal>
    </Space>
  )
}
